package com.qoupon.client;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {

	public static final int NOTIFICATION_ID = 237;
	private static final String TAG = "[GroupIn]GCMIntentService";
	private PushPlugin mPushPlugin;
	private MyDataBaseHelper myDbHelper;
	
	public GCMIntentService() {
		super("GCMIntentService");
	}

	@Override
	public void onRegistered(Context context, String regId) {

		Log.v(TAG, "onRegistered: "+ regId);

		JSONObject json;

		try
		{
			json = new JSONObject().put("event", "registered");
			json.put("regid", regId);

			Log.v(TAG, "onRegistered: " + json.toString());

			// Send this JSON data to the JavaScript application above EVENT should be set to the msg type
			// In this case this is the registration ID
			PushPlugin.sendJavascript( json );

		}
		catch( JSONException e)
		{
			// No message to the user is sent, JSON failed
			Log.e(TAG, "onRegistered: JSON exception");
		}
	}

	@Override
	public void onUnregistered(Context context, String regId) {
		Log.d(TAG, "onUnregistered - regId: " + regId);
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		Log.d(TAG, "onMessage - context: " + context);

		// Extract the payload from the message
		Bundle extras = intent.getExtras();
		if (extras != null)
		{
			JSONObject push_noti_object=convertBundleDataToJSON(extras);
			pushDataToDB(push_noti_object);
			// if we are in the foreground, just surface the payload, else post it to the statusbar
            if (PushPlugin.isInForeground()) {
				extras.putBoolean("foreground", true);
                PushPlugin.sendExtras(extras);
			}
			else {
				extras.putBoolean("foreground", false);

                // Send a notification if there is a message
                if (extras.getString("message") != null && extras.getString("message").length() != 0) {
                    createNotification(context, push_noti_object);
                }
            }
        }
	}

	private void pushDataToDB(JSONObject jsonObject) {
		myDbHelper = new MyDataBaseHelper(this);
		
		/**
		 * CRUD Operations
		 * */
		// Inserting PushData
		Log.d("Insert: ", "Inserting ..");
		try {
			myDbHelper.addPushData(new PushData(jsonObject.getString("message_id"),jsonObject.getString("companyName"),jsonObject.toString(),"N"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private JSONObject convertBundleDataToJSON(Bundle extras) {
		// TODO Auto-generated method stub
		JSONObject reader;
		JSONObject push_noti_object = null;
		String message = extras.getString("message");
		Log.e(TAG, "message : " + message);
		try {
			reader = new JSONObject(message);
			push_noti_object  = reader.getJSONObject("push_data");
			} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	return push_noti_object;
	}

	public void createNotification(Context context, JSONObject push_noti_object)
	{
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		String appName = getAppName(this);

		Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		notificationIntent.putExtra("pushBundle", push_noti_object.toString());

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		
		String senderName = "";
		String companyName = "";
	

		
		try {
			senderName = push_noti_object.getString("messageSenderName");
			companyName = push_noti_object.getString("companyName");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	

		Notification noti = null;
		Notification.Builder builder = new Notification.Builder(context);
		builder.setContentTitle(context.getString(R.string.app_name))
		.setContentText(companyName)
		.setWhen(System.currentTimeMillis())
		.setTicker(senderName)
		.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.simple_quick_icon))
		.setSmallIcon(R.drawable.simple_quick_icon)
		.setContentIntent(contentIntent);
	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
		noti = builder.getNotification();
	} else {
		noti = builder.build();
	}
	 noti.flags |= Notification.DEFAULT_SOUND;
	 mNotificationManager.notify((String) appName, NOTIFICATION_ID, noti);
		
		
	}

	public static void cancelNotification(Context context)
	{
		NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel((String)getAppName(context), NOTIFICATION_ID);	
	}
	
	private static String getAppName(Context context)
	{
		CharSequence appName = 
				context
					.getPackageManager()
					.getApplicationLabel(context.getApplicationInfo());
		
		return (String)appName;
	}
	
	@Override
	public void onError(Context context, String errorId) {
		Log.e(TAG, "onError - errorId: " + errorId);
	}

}
